// src/store/slices/voiceSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import aiService from '../../services/aiService';
import fileService from '../../services/fileService';
import { VoiceRecord } from '../../types';

interface VoiceState {
  isRecording: boolean;
  isPaused: boolean;
  recordTime: number;
  audioPath: string | null;
  transcript: string;
  isProcessing: boolean;
  error: string | null;
  selectedLanguage: string;
  records: VoiceRecord[];
  currentRecord: VoiceRecord | null;
  usageToday: number;
  usageLimit: number;
}

const initialState: VoiceState = {
  isRecording: false,
  isPaused: false,
  recordTime: 0,
  audioPath: null,
  transcript: '',
  isProcessing: false,
  error: null,
  selectedLanguage: 'zh-CN',
  records: [],
  currentRecord: null,
  usageToday: 0,
  usageLimit: 5,
};

// 异步actions
export const processAudio = createAsyncThunk(
  'voice/processAudio',
  async ({ audioPath, language }: { audioPath: string; language?: string }) => {
    // 上传音频
    const audioUrl = await fileService.uploadAudio(audioPath);

    // 语音转文字
    const response = await aiService.voiceToText({
      audioUrl,
      language,
    });

    return {
      audioUrl,
      ...response,
    };
  }
);

export const loadVoiceHistory = createAsyncThunk(
  'voice/loadHistory',
  async ({ page = 1 }: { page?: number } = {}) => {
    const response = await aiService.getVoiceHistory(page);
    return response;
  }
);

export const textToSpeech = createAsyncThunk(
  'voice/textToSpeech',
  async ({ text, voice, speed }: { text: string; voice?: string; speed?: number }) => {
    const audioUrl = await aiService.textToVoice(text, voice, speed);
    return audioUrl;
  }
);

const voiceSlice = createSlice({
  name: 'voice',
  initialState,
  reducers: {
    startRecording: (state) => {
      state.isRecording = true;
      state.isPaused = false;
      state.recordTime = 0;
      state.transcript = '';
      state.error = null;
    },
    pauseRecording: (state) => {
      state.isPaused = true;
    },
    resumeRecording: (state) => {
      state.isPaused = false;
    },
    stopRecording: (state, action: PayloadAction<string>) => {
      state.isRecording = false;
      state.isPaused = false;
      state.audioPath = action.payload;
    },
    updateRecordTime: (state, action: PayloadAction<number>) => {
      state.recordTime = action.payload;
    },
    setTranscript: (state, action: PayloadAction<string>) => {
      state.transcript = action.payload;
    },
    setSelectedLanguage: (state, action: PayloadAction<string>) => {
      state.selectedLanguage = action.payload;
    },
    addRecord: (state, action: PayloadAction<VoiceRecord>) => {
      state.records.unshift(action.payload);
      if (state.records.length > 50) {
        state.records.pop();
      }
    },
    setCurrentRecord: (state, action: PayloadAction<VoiceRecord | null>) => {
      state.currentRecord = action.payload;
      if (action.payload) {
        state.transcript = action.payload.transcript;
      }
    },
    deleteRecord: (state, action: PayloadAction<string>) => {
      state.records = state.records.filter((r) => r.id !== action.payload);
      if (state.currentRecord?.id === action.payload) {
        state.currentRecord = null;
      }
    },
    clearRecords: (state) => {
      state.records = [];
      state.currentRecord = null;
    },
    clearError: (state) => {
      state.error = null;
    },
    resetVoice: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      // Process Audio
      .addCase(processAudio.pending, (state) => {
        state.isProcessing = true;
        state.error = null;
      })
      .addCase(processAudio.fulfilled, (state, action) => {
        state.isProcessing = false;
        state.transcript = action.payload.text;
        state.usageToday += 1;

        // 创建记录
        const record: VoiceRecord = {
          id: Date.now().toString(),
          audioUrl: action.payload.audioUrl,
          transcript: action.payload.text,
          duration: state.recordTime,
          timestamp: new Date(),
        };

        state.records.unshift(record);
        state.currentRecord = record;
      })
      .addCase(processAudio.rejected, (state, action) => {
        state.isProcessing = false;
        state.error = action.error.message || '处理失败';
      })
      // Load History
      .addCase(loadVoiceHistory.fulfilled, (state, action) => {
        state.records = action.payload.records;
      });
  },
});

export const {
  startRecording,
  pauseRecording,
  resumeRecording,
  stopRecording,
  updateRecordTime,
  setTranscript,
  setSelectedLanguage,
  addRecord,
  setCurrentRecord,
  deleteRecord,
  clearRecords,
  clearError,
  resetVoice,
} = voiceSlice.actions;

export default voiceSlice.reducer;